package com.zhongshengnetwork.rightbe.qrcode;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.ContactsContract;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.Constant.Constant;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.MainActivity;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.BackAES;
import com.zhongshengnetwork.rightbe.common.Base64;
import com.zhongshengnetwork.rightbe.common.CircleTransform;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.Des;
import com.zhongshengnetwork.rightbe.common.PermissionUtils;
import com.zhongshengnetwork.rightbe.common.ScreenUtils;
import com.zhongshengnetwork.rightbe.common.TopBarView;
import com.zhongshengnetwork.rightbe.common.activity.AppBaseActivity;
import com.zhongshengnetwork.rightbe.common.callback.PermissionCallback;
import com.zhongshengnetwork.rightbe.common.customview.ActionSheetDialog;
import com.zhongshengnetwork.rightbe.dbservice.LetterdbService;
import com.zhongshengnetwork.rightbe.login.LoginActivity;
import com.zhongshengnetwork.rightbe.my.activity.MyInfoActivity;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zhongshengnetwork.rightbe.qrcode.tools.QRCodeUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import static com.zhongshengnetwork.rightbe.MainActivity.REQ_PERM_EXTERNAL_STORAGE;

//三检查OK:2016-11-30
public class QRCodeActivity extends AppBaseActivity implements TopBarView.onTitleBarClickListener{
    private TopBarView topbar;
    private ImageView qrcodeImageView;
    private ImageView headerImg;
    private TextView nameText;
    private ImageView iconImg;
    private TextView contentText;
    private TextView bottomText;
    private ImageView centerImg;
    private String id;
    private String header;
    private String name;
    private String content;
    private int type;
    private RelativeLayout qrcode_img_layout;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        id = getIntent().getStringExtra(APIKey.idKey);
        header = getIntent().getStringExtra(APIKey.headerKey);
        name = getIntent().getStringExtra(APIKey.nameKey);
        content = getIntent().getStringExtra(APIKey.contentKey);
        type = getIntent().getIntExtra(APIKey.typeKey,0);
        setContentView(R.layout.activity_qrcode);
        qrcode_img_layout = (RelativeLayout) findViewById(R.id.qrcode_img_layout);
        topbar = (TopBarView)findViewById(R.id.topbar);
        topbar.setClickListener(this);
        topbar.getRightView().setImageResource(R.drawable.more);
        topbar.getRightView().setClickable(true);
        topbar.getRightView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (CommonUtils.isLogin() == false){
                    Intent intent = new Intent(QRCodeActivity.this, LoginActivity.class);
                    startActivity(intent);
                    return;
                }

                PermissionUtils.isPictureNote(QRCodeActivity.this, new PermissionCallback() {
                    @Override
                    public void onResult(boolean flag, boolean showAlert) {
                        if (flag == true){
                            // 申请文件读写权限（部分朋友遇到相册选图需要读写权限的情况，这里一并写一下）
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU){
                                if (ContextCompat.checkSelfPermission(QRCodeActivity.this, Manifest.permission.READ_MEDIA_IMAGES) != PackageManager.PERMISSION_GRANTED){
                                    ActivityCompat.requestPermissions(QRCodeActivity.this, new String[]{Manifest.permission.READ_MEDIA_AUDIO, Manifest.permission.READ_MEDIA_IMAGES},
                                            MainActivity.REQUEST_PERMISSION);
                                    return;
                                }
                            }else if (ActivityCompat.checkSelfPermission(QRCodeActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                                // 申请权限
                                ActivityCompat.requestPermissions(QRCodeActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQ_PERM_EXTERNAL_STORAGE);
                                return;
                            }
                            final List<String> menu = new ArrayList<String>();
                            menu.add("保存");
                            ActionSheetDialog actionSheetDialog = new ActionSheetDialog(QRCodeActivity.this)
                                    .builder()
                                    .setTitle("")
                                    .setCancelable(false)
                                    .setCanceledOnTouchOutside(true);
                            for (String m : menu){
                                actionSheetDialog.addSheetItem(m, null, new ActionSheetDialog.OnSheetItemClickListener() {
                                    @Override
                                    public void onClick(int which) {
                                        if (which == 1){
                                            final Bitmap bitmap = viewConversionBitmap(qrcode_img_layout);
                                            if (bitmap != null){
                                                CommonUtils.saveBmp2Gallery(bitmap,System.currentTimeMillis()+"");
                                            }
                                        }
                                    }
                                });
                            }
                            actionSheetDialog.show();
                        }
                    }
                });


            }
        });


        headerImg = (ImageView) findViewById(R.id.activity_qrcode_upheader);
        Glide.with(QRCodeActivity.this).load(header).transform(new CircleTransform(QRCodeActivity.this)).dontAnimate().into(headerImg);
        nameText = (TextView) findViewById(R.id.activity_qrcode_name);
        nameText.setText(name);
        iconImg = (ImageView) findViewById(R.id.activity_qrcode_icon);
        contentText = (TextView) findViewById(R.id.activity_qrcode_area);
        contentText.setText(content);
        bottomText = (TextView) findViewById(R.id.activity_qrcode_bottomtext);
        ImageView groupbg = (ImageView) findViewById(R.id.activity_qrcode_upheader_bg);
        ImageView groupcenterbg = (ImageView) findViewById(R.id.activity_qrcode_centerheaderbg);
        if (type == 0){
            bottomText.setText("言微句美发现共鸣，记录生活记录你");
            groupbg.setVisibility(View.INVISIBLE);
            groupcenterbg.setVisibility(View.INVISIBLE);
        }else {
            bottomText.setText("扫一扫上面的二维码，加入该团");
            groupbg.setVisibility(View.VISIBLE);
            groupcenterbg.setVisibility(View.VISIBLE);
        }
        centerImg = (ImageView) findViewById(R.id.activity_qrcode_centerheader);
        Glide.with(QRCodeActivity.this).load(header).transform(new CircleTransform(QRCodeActivity.this)).dontAnimate().into(centerImg);
        qrcodeImageView = (ImageView) findViewById(R.id.activity_qrcode_qrimg);
        final String filePath = getFileRoot(QRCodeActivity.this) + File.separator
                + "qr_" + System.currentTimeMillis() + ".jpg";

        //二维码图片较大时，生成图片、保存文件的时间可能较长，因此放在新线程中
        new Thread(new Runnable() {
            @Override
            public void run() {
                String content = Constant.QRCodeHOST+"downapp.do?";
                if(type == 0){//人
                    content = Constant.QRCodeHOST+"qrcode.do?";
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put(APIKey.useridKey,id);
                    jsonObject.put(APIKey.timeKey, System.currentTimeMillis()+"");
                    String code = jsonObject.toString();
                    try {
                        code = Des.encryptDES(code,Constant.DESKey);
                        content += code;
                    }catch (Exception e){
                        return;
                    }

                }else {//团
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put(APIKey.groupidKey,id);
                    String code = jsonObject.toString();
                    try {
                        code = Des.encryptDES(code,Constant.DESKey);
                        content += code;
                    }catch (Exception e){
                        return;
                    }
                }
                int W = dip2px(QRCodeActivity.this,ScreenUtils.getScreenWidth(QRCodeActivity.this));
                boolean success = QRCodeUtil.createQRImage(content, W, W,
                        null,
                        filePath);

                if (success) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            qrcodeImageView.setImageBitmap(BitmapFactory.decodeFile(filePath));
                        }
                    });
                }
            }
        }).start();

    }

    private static Bitmap viewConversionBitmap(View v) {
        int w = v.getWidth();
        int h = v.getHeight();
        Log.e("TAG", "width: " + w + " height: " + h);
        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bmp);

        c.drawColor(Color.WHITE);
        /** 如果不设置canvas画布为白色，则生成透明 */

        //v.layout(0, 0, w, h);
        v.draw(c);

        return bmp;
    }


    //文件存储根目录
    private String getFileRoot(Context context) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File external = context.getExternalFilesDir(null);
            if (external != null) {
                return external.getAbsolutePath();
            }
        }
        return context.getFilesDir().getAbsolutePath();
    }

    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 点击了返回导航按钮
     */
    @Override
    public void onBackClick() {
        //Toast.makeText(LoginActivity.this, "你点击了左侧按钮", Toast.LENGTH_LONG).show();
        finish();
    }

    /**
     * 点击了右边导航按钮
     */
    @Override
    public void onRightClick() {

    }

}
